package com.varton.registry;

import com.varton.registry.zk.ZkConfig;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class RegistryCenterImpl implements RegistryCenter{
    private CuratorFramework framework;

    {
        framework = CuratorFrameworkFactory.builder().connectString(ZkConfig.ZK_ADDR).sessionTimeoutMs(4000)
                .retryPolicy(new ExponentialBackoffRetry(1000,3)).build();
        framework.start();
    }

    @Override
    public void registry(String serviceName, String address) {
        try {
            String servicePath = ZkConfig.ROOT_NODE+"/"+serviceName;
            if (framework.checkExists().forPath(servicePath) == null){
                framework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(servicePath,"0".getBytes());
            }
            String node = framework.create().withMode(CreateMode.EPHEMERAL).forPath(servicePath+"/"+address,"0".getBytes());
            System.out.println("注册服务成功:"+node);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
